<template>
    <div class="login-container">
        <div class="right-opera">
            <a-tabs v-model="activeName" default-active-key="password" @change="callback">
                <a-tab-pane key="password" tab="密码登录"></a-tab-pane>
                <a-tab-pane key="code" tab="快捷登录"></a-tab-pane>
            </a-tabs>
            <a-form-model ref="loginForm" class="login-form" :model="form" :rules="rules">
                <a-form-model-item prop="account">
                    <a-input
                        v-model="form.account"
                        @keyup.enter.native="onSubmit"
                        :placeholder="activeName === 'password' ? '请输入手机号/账号' : '请输入手机号'"
                    >
                        <img
                            src="~/assets/images/login-user.png"
                            slot="prefix"
                            alt=""
                            v-if="activeName === 'password'"
                            class="prefix-image"
                        />
                        <img src="~/assets/images/login-tel.png" slot="prefix" alt="" class="prefix-image" v-else />
                    </a-input>
                </a-form-model-item>
                <a-form-model-item prop="password" v-if="activeName === 'password'">
                    <a-input
                        v-model="form.password"
                        @keyup.enter.native="onSubmit"
                        placeholder="请输入密码"
                        type="password"
                    >
                        <img class="prefix-image" src="~/assets/images/login-password.png" slot="prefix" alt="" />
                    </a-input>
                </a-form-model-item>
                <a-form-model-item prop="verificationCode" class="send-verificationCode" v-else>
                    <a-input
                        v-model="form.verificationCode"
                        @keyup.enter.native="onSubmit"
                        class="verificationCode-input"
                        placeholder="请输入验证码"
                    >
                        <img class="prefix-image2" src="~/assets/images/login-email.png" slot="prefix" alt="" />
                    </a-input>
                    <a-button type="link" class="btn" :disabled="!!second" @click="getCode">
                        获取验证码{{ second ? '&emsp;' + second : '' }}
                    </a-button>
                </a-form-model-item>
                <a-form-model-item class="login-btn-item">
                    <a-button type="primary" class="login-btn" @click="onSubmit" :loading="loading"> 登录 </a-button>
                </a-form-model-item>
            </a-form-model>
            <div class="bottom-btn">
                <a-button type="link" @click="forgetPassword">找回密码</a-button>
                <a-button type="link" @click="freeRegister">免费注册</a-button>
            </div>
            <div class="other-login">
                <!--                <p>其他登录方式</p>-->
                <!--                <div class="img" @click="toWechat"></div>-->
                <div class="QR-code" v-if="imgUrl">
                    <img :src="`data:image/png;base64,${imgUrl}`" alt="" />
                    <p>扫码APP下载</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { localStorage } from '~/plugins/tools'

export default {
    name: 'Login',
    layout: 'login-layout',
    data () {
        const checkTel = (rule, value, callback) => {
            if (this.activeName === 'password') {
                callback()
            } else if (!/^1[3456789]\d{9}$/.test(value)) {
                callback(new Error('请输入正确的手机号'))
            } else {
                callback()
            }
        }

        return {
            activeName: 'password',
            form: {
                account: '',
                password: '',
                verificationCode: ''
            },
            rules: {
                account: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { validator: checkTel, trigger: 'change' }
                ],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
                verificationCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
            },
            second: 0,
            timer: null,
            loading: false,
            imgUrl: ''
        }
    },
    created () {
        if (process.client) {
            window.localStorage.clear()
        }
        const query = this.$route.query
        if (query && query.code && query.state) {
            this.toWechatLogin(query)
        }
        this.getImg()
    },
    methods: {
        callback () {
            this.$refs.loginForm.resetFields()
        },
        async getImg () {
            const res = await this.$ApiServer['home/getCode']()
            this.imgUrl = res.data
        },
        async getCompanyState () {
            const res = await this.$ApiServer['company/state/info']()
            if (res.code === 200) {
                return res.data
            }
        },
        onSubmit () {
            this.$refs.loginForm.validate(async (valid) => {
                if (valid) {
                    this.loading = true
                    const { account, password, verificationCode } = this.form
                    let data = {}
                    let url = ''
                    if (this.activeName === 'password') {
                        data = {
                            password,
                            username: account
                        }
                        url = 'login'
                    } else {
                        data = {
                            username: account,
                            smscode: verificationCode
                        }
                        url = 'login/code'
                    }
                    const res = await this.$ApiServer[url](data)
                    this.loading = false
                    if (res.code === 200) {
                        this.$store.dispatch('user/setUserInfo', res.data).then(async () => {
                            this.$message.success(res.message)
                            const result = await this.getCompanyState()
                            localStorage.setItem('companyAuth', result)
                            if (res.data.orgCategoryId === '4') {
                                const resp = await this.$ApiServer['user/companyInfo']()
                                if ((res.data.companyId === '0' || !res.data.companyId) && !result.companyInfoState) {
                                    this.$router.push('/welcome')
                                } else if (result.companyInfoState && !result.companyState) {
                                    this.$router.push('/company-auth')
                                } else if (!result.companyInfoState && result.companyState) {
                                    this.$router.push('/settled')
                                } else if (result.companyInfoState && result.companyState && !resp.data) {
                                    this.$router.push('/company-manage/company-info')
                                } else {
                                    this.$router.push('/home')
                                }
                            } else if (res.data.orgCategoryId === '3' || res.data.orgCategoryId === '2') {
                                this.$router.push('/operate')
                            } else {
                                this.$router.push('/home')
                            }
                        })
                    } else {
                        this.$message.error(res.message)
                    }
                }
            })
        },
        async getCode () {
            const res = await this.$ApiServer['login/sendSmsCode']({
                username: this.form.account
            })
            if (res.code === 200) {
                this.$message.success('发送成功')
                this.second = 60
                this.timer = setInterval(() => {
                    if (this.second) {
                        this.second--
                    } else {
                        clearInterval(this.timer)
                    }
                }, 1000)
            } else {
                this.$message.error(res.message)
            }
        },
        forgetPassword () {
            this.$router.push('/auth/forget-password')
        },
        freeRegister () {
            this.$router.push('/auth/register')
        },
        async toWechat () {
            const res = await this.$ApiServer['login/wechat/qr']()
            window.location.href = res.data
        },
        async toWechatLogin (query) {
            const { code, state } = query
            const res = await this.$ApiServer['login/wechat']({
                wxcode: code,
                wxstate: state,
                type: 1
            })
            if (res.code === 2006) {
                this.$router.push({
                    path: '/auth/bind-account',
                    query: {
                        code,
                        state
                    }
                })
            } else if (res.code === 200) {
                this.$store.dispatch('user/setUserInfo', res.data).then(async () => {
                    this.$message.success(res.message)
                    const result = await this.getCompanyState()
                    localStorage.setItem('companyAuth', result)
                    if (res.data.orgCategoryId === '4') {
                        const resp = await this.$ApiServer['user/user/companyInfo']()
                        if ((res.data.companyId === '0' || !res.data.companyId) && !result.companyInfoState) {
                            this.$router.push('/welcome')
                        } else if (result.companyInfoState && !result.companyState) {
                            this.$router.push('/company-auth')
                        } else if (!result.companyInfoState && result.companyState) {
                            this.$router.push('/settled')
                        } else if (result.companyInfoState && result.companyState && !resp.data) {
                            this.$router.push('/company-manage/company-info')
                        } else {
                            this.$router.push('/home')
                        }
                    } else if (res.data.orgCategoryId === '3' || res.data.orgCategoryId === '2') {
                        this.$router.push('/operate')
                    } else {
                        this.$router.push('/home')
                    }
                })
            } else {
                this.$message.error(res.message)
            }
        }
    }
}
</script>

<style lang="less" scoped src="./index.less"></style>
